<?php

/*
* @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
* @Date: 2022-03-14 15:13:28
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-03-16 17:19:28
* @Description: File Description
*/

namespace rainlee\auth;

use think\facade\Config;
use think\helper\Str;

class Recaller
{
    protected $passphrase;

    protected $recaller;

    public function __construct()
    {
        $this->passphrase = Config::get('auth.app_key');
    }

    /**
     * 获取用户ID
     *
     * @return string
     */
    public function id()
    {
        return explode('|', $this->recaller, 2)[0];
    }

    /**
     * 获取remember token字符串
     *
     * @return string
     */
    public function token()
    {
        return explode('|', $this->recaller, 2)[1];
    }

    /**
     * 验证recaller
     *
     * @return bool
     */
    public function valid()
    {
        return $this->properString() && $this->hasAllSegments();
    }

    /**
     * 验证recaller是否为有效字符串
     *
     * @return bool
     */
    protected function properString()
    {
        return is_string($this->recaller) && Str::contains($this->recaller, '|');
    }

    /**
     * 验证recaller是否符合规则
     *
     * @return bool
     */
    protected function hasAllSegments()
    {
        $segments = explode('|', $this->recaller);

        return count($segments) == 2 && trim($segments[0]) !== '' && trim($segments[1]) !== '';
    }

    /**
     * 加密
     * 
     * @return string
     */
    public function encrype($recaller)
    {
        return openssl_encrypt($recaller, 'DES-ECB', $this->passphrase, 0);
    }

    /**
     * 解密
     * 
     * @return
     */
    public function decrypt($recaller)
    {
        $this->recaller = openssl_decrypt($recaller, 'DES-ECB', $this->passphrase, 0);
        return $this;
    }
}
